﻿using AngleSharp.Css;
using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Models;
using RndMaterialDisposalService.Services;
using RndMaterialDisposalService.Services.Interface;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient.Server;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;
using Newtonsoft.Json.Linq;
using System.Text.Json.Nodes;

namespace RndMaterialDisposalService.Controllers
{
    /// <summary>
    /// K2SmartObject
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SMOController : ControllerBase
    {
        private readonly ILogger<SMOController> logger;
        private readonly IDataDictionaryService dictService;
        private readonly ISMOService ISMOService;
        private readonly IWorkflowCommon workflowCommon;
        private readonly IConfiguration configuration;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        /// <param name="_workflowCommon"></param>
        /// <param name="_dictService"></param>
        /// <param name="_ISMOService"></param>
        /// <param name="_configuration"></param>
        public SMOController(ILogger<SMOController> _logger, IWorkflowCommon _workflowCommon, 
            IDataDictionaryService _dictService, ISMOService _ISMOService, IConfiguration _configuration)
        {
            logger = _logger;
            dictService = _dictService;
            ISMOService = _ISMOService;
            workflowCommon = _workflowCommon;
            configuration = _configuration;
        }

        /// <summary>
        /// 根据procInstId获取审批人
        /// </summary>
        /// <param name="procInstId">流程实例Id</param>
        /// <param name="parentCode">数据字典父类code</param>
        /// <param name="activeName">环节名称code</param>
        /// <returns></returns>
        [HttpGet("GetApprovlUser")]
        [PageList]
        public async Task<List<string>> GetApprovlUser(int procInstId,Guid parentCode,string activeName)
        {
            List<string> userList = new();
            var dicList = await dictService.GetDictItems(parentCode);
            var dic = dicList.FirstOrDefault(x => x.Code == activeName);
            var fieldPath = dic?.Value;
            try
            {
                if (!string.IsNullOrEmpty(fieldPath))
                {
                    var applicationData = await ISMOService.GetApplicationData(procInstId.ToString());
                    JObject job = JObject.Parse(applicationData.FormData);
                    string userField = job.SelectToken(fieldPath).ToString();
                    if (!string.IsNullOrEmpty(userField))
                    {
                        var listTemp = userField.Split(";");
                        var listTempLabel = listTemp.Select(x => x = $"K2:EDPDM\\{x}");
                        userList.AddRange(listTempLabel);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"没有找到节点审批人,procInstId {procInstId},parentCode {parentCode},activeName {activeName},fieldPath {fieldPath}");
                throw ex;
            }
            
            return userList;
        }

        /// <summary>
        /// 根据formid获取审批人
        /// </summary>
        /// <param name="formId"></param>
        /// <param name="parentCode"></param>
        /// <param name="activeName"></param>
        /// <returns></returns>
        [HttpGet("GetApprovlUserByFormId")]
        [PageList]
        public async Task<List<string>> GetApprovlUserByFormId(int formId, Guid parentCode, string activeName)
        {
            List<string> userList = new();
            var dicList = await dictService.GetDictItems(parentCode);
            var dic = dicList.FirstOrDefault(x => x.Code == activeName);
            var fieldPath = dic?.Value;
            if (!string.IsNullOrEmpty(fieldPath))
            {
                var applicationData = await ISMOService.GetApplicationDataByFormId(formId);
                JObject job = JObject.Parse(applicationData.FormData);
                string userField = job.SelectToken(fieldPath).ToString();
                if (!string.IsNullOrEmpty(userField))
                {
                    var listTemp = userField.Split(";");
                    var listTempLabel = listTemp.Select(x => x = $"K2:EDPDM\\{x}");
                    userList.AddRange(listTempLabel);
                }
            }

            //logger.LogInformation($"GetApprovlUserByFormId,formId:{formId},parentCode:{parentCode},activeName:{activeName},Result:{userList}");
            return userList;
        }

        /// <summary>
        /// 更新表单状态
        /// </summary>
        /// <param name="procInstId"></param>
        /// <param name="currentStatus"></param>
        /// <param name="currentUserID"></param>
        /// <returns></returns>
        [HttpPost("UpdateApplicationCurrentStatus")]
        [PageList]
        public async Task<int> UpdateApplicationCurrentStatus(int procInstId, string currentStatus, string currentUserID)
        {
            logger.LogInformation($"UpdateApplicationCurrentStatus,procInstId:{procInstId},currentStatus:{currentStatus},currentUserID:{currentUserID}");
            return await ISMOService.UpdateApplicationCurrentStatus(procInstId, currentStatus, currentUserID);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="procInstId"></param>
        /// <param name="currentActivity"></param>
        /// <param name="moduleName"></param>
        /// <param name="functionName"></param>
        /// <returns></returns>
        [HttpPost("UpdateToDoCurrentActivity")]
        [PageList]
        public async Task<int> UpdateToDoCurrentActivity(int procInstId, string currentActivity, string moduleName, string functionName)
        {
            logger.LogInformation($"UpdateToDoCurrentActivity,procInstId:{procInstId},currentActivity:{currentActivity},moduleName:{moduleName},functionName:{functionName}");
            return await ISMOService.UpdateToDoCurrentActivity(procInstId, currentActivity, moduleName,functionName);
        }

        /// <summary>
        /// 资产管理
        /// </summary>
        /// <param name="procInstId"></param>
        /// <param name="functionUrl"></param>
        /// <param name="currentStatus"></param>
        /// <returns></returns>
        [HttpPost("UpdateToDo")]
        [PageList]
        public async Task<int> UpdateToDo(int procInstId, string functionUrl, string currentStatus)
        {
            logger.LogInformation($"SMOController.UpdateToDo,procInstId:{procInstId},,currentStatus:{currentStatus},functionUrl:{functionUrl}");
            var formUrl = new Uri(functionUrl);
            var newUrl = $"{configuration.GetSection("WebPortalHost").Value}/{formUrl.Fragment}";
            await workflowCommon.UpdataWorklistHeader(procInstId.ToString(), newUrl);
            return await ISMOService.UpdateToDo(procInstId, newUrl, currentStatus);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="procInstId"></param>
        /// <param name="functionUrl"></param>
        /// <param name="currentStatus"></param>
        /// <param name="appName">区分应用</param>
        /// <returns></returns>
        [HttpPost("UpdateToDoNew")]
        [PageList]
        public async Task<int> UpdateToDoNew(int procInstId, string functionUrl, string currentStatus, string appName)
        {
            logger.LogInformation($"SMOController.UpdateToDo,procInstId:{procInstId},,currentStatus:{currentStatus},functionUrl:{functionUrl}");
            var formUrl = new Uri(functionUrl);
            var newUrl = $"{configuration.GetSection(appName).Value}/{formUrl.Fragment}";
            await workflowCommon.UpdataWorklistHeader(procInstId.ToString(), newUrl);

            return await ISMOService.UpdateToDo(procInstId, newUrl, currentStatus);
        }

    }
}
